﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header{
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/fileinput/5.0.3/css/fileinput.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/fileinput/5.0.3/js/fileinput.min.js"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/summernote/0.8.15/summernote.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/summernote/0.8.15/summernote.js"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/summernote/0.8.15/lang/summernote-zh-CN.min.js"))

<style>
    .krajee-default .file-thumb-progress .progress, .krajee-default .file-thumb-progress .progress-bar {
        height: 16px;
    }
</style>
}
<div class="wrapper animated fadeInRight">
    <form id="form" class="form-horizontal m">
        <div class="form-group">
            <label class="col-sm-2 control-label" id="planName">计划名称<font class="red"> *</font></label>
            <div class="col-sm-10">
                <input id="name" col="Name" type="text" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">性别<font class="red"> *</font></label>
            <div class="col-sm-10" id="sex" col="Sex"></div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">年龄<font class="red"> *</font></label>
            <div class="col-sm-10" id="age" col="Age">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">推广开始时间<font class="red"> *</font></label>
            <div class="col-sm-10">
                <input type="text" id="starttime" col="StartTime" placeholder="H点m分" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">推广结束时间<font class="red"> *</font></label>
            <div class="col-sm-10 ">
                <input type="text" id="endtime" col="EndTime" placeholder="H点m分" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">创意标题一<font class="red"> *</font></label>
            <div class="col-sm-10">
                <input id="chuangyio" col="ChuangYio" type="text" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">创意标题二&nbsp;&nbsp;</label>
            <div class="col-sm-10">
                <input id="chuangyit" col="ChuangYit" type="text" class="form-control" />
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">创意内容&nbsp;&nbsp;</label>
            <div class="col-sm-10">
                <div class="ibox float-e-margins">
                    <div class="ibox-content no-padding">
                        <div class="summernote" id="contents" col="Contents">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label ">投放地区<font class="red"> *</font></label>
            <div class="col-sm-10">
                <div id="area" class="ztree"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">推广链接<font class="red"> *</font></label>
            <div class="col-sm-10">
                <input id="link" col="Link" type="text" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">推广图片&nbsp;&nbsp;</label>
            <div class="col-sm-10">
                <input name="fileUrl" class="form-control" type="hidden" />
                <input name="host" class="form-control" type="hidden" />
                <div class="file-loading">
                    <input id="fileinput-demo-2" type="file" multiple>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label">每日预算<font class="red"> *</font></label>
            <div class="col-sm-10">
                <input id="budget" col="Budget" type="text" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">启用状态<font class="red"> *</font></label>
            <div id="setswitch" col="SetSwitch" class="col-sm-10"></div>
        </div>
    </form>
</div>

<script type="text/javascript">
               var id = ys.request("id");
               var picList=[];
               var initialPreview = [] ;
               var initialPreviewConfig = [] ;

               $(function () {
                    $('.summernote').summernote({
                         lang: 'zh-CN',
                         height:150,
                         'toolbar':[
                                    ['style', ['style']],
                                    ['font', ['bold', 'italic', 'underline', 'clear']],
                                    ['fontname', ['fontname']],
                                    ['color', ['color']],
                                    ['para', ['ul', 'ol', 'paragraph']],
                                    ['height', ['height']],
                                    ['table', ['table']],
                                    ['insert', ['hr']],
                                    ['view', [ 'codeview']],
                                    ['help', ['help']]
    ]
                     });

                      $("#setswitch").ysRadioBox({ data: ys.getJson(@Html.Raw(typeof(StatusEnum).EnumToDictionaryString())) });
                      $("#sex").ysRadioBox({ data: ys.getJson(@Html.Raw(typeof(YiSha.Enum.OrganizationManage.GenderTypeEnum).EnumToDictionaryString())) });

                       var selectdata = [
                       { 'Key': '1-17', 'Value': '1-17' },
                       { 'Key': '18-23', 'Value': '18-23' },
                       { 'Key': '24-30', 'Value': '24-30' },
                       { 'Key': '31-40', 'Value': '31-40' },
                       { 'Key': '41-49', 'Value': '41-49' },
                       { 'Key': '50+', 'Value': '50+' }
                   ];

                    $("#age").ysComboBox({
                       data: selectdata,
                       class: "form-control",
                       multiple: true
                    });

                    loadMenuTree();
                    getForm();

                    var startDate = laydate.render({
                                elem: '#starttime',
                                type:'time',
                                trigger: 'click',
                                max:"2099-12-31",//设置一个默认最大值、
                                position:'fixed',
                                done: function(value, date) {
                                    // 结束时间大于开始时间
                                    endDate.config.min ={
                                        year:date.year,
                                        month:date.month-1, //关键
                                        date: date.date,
                                        hours: date.hours+1,
                                        minutes:date.minutes,
                                        seconds :date.seconds
                                    };
                                }
                            });
                    var endDate = laydate.render({
                        elem: '#endtime',
                        type: 'time',
                        min:"1970-1-1",//设置min默认最小值
                        trigger: 'click',
                        position:'fixed',
                        done: function(value, date) {
                            // 开始时间小于结束时间
                            startDate.config.max={
                                year:date.year,
                                month:date.month-1,//关键
                                date: date.date,
                                hours: date.hours-1 ,
                                minutes:date.minutes,
                                seconds :date.seconds
                            }
                        }
                    });



                 $("#fileinput-demo-2").fileinput(
                                                  {
                                                     language: 'zh',
                                                    uploadUrl: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.News.ParseToInt()',
                                                    maxFileCount: 5,
                                                    autoReplace: true,
                                                    showClose: false, //隐藏右上角叉
                                                    showRemove: false, //隐藏清除按钮
                                                    //uploadExtraData: { modeId:modeId },
        	                                        initialPreview: initialPreview,
         	                                        initialPreviewConfig: initialPreviewConfig,
			                                        initialPreviewAsData: true, // defaults markup
                                                    fileSizeGetter:true,
                                                    overwriteInitial:false
        
                                                 })
                                                .on("filebatchselected", doUpload())
                                                .on("fileuploaded", function (event, data, previewId, index) {
                                                    // 文件上传成功
                                                    const result = data.response
                                                    // 文件上传完成  key即为相对路径
                                                  picList.push({'path':result.Data,'previewId':previewId});
                                               
                                                }).on("filesuccessremove", function (event,previewId) {

                                                    // 上传完成后, 移除成功通知
			                                        for (var i = 0; i < picList.length; i++) { 
			                                              if (picList[i].previewId== previewId) { 
 			                                                  picList.splice(i,1);
			                                              } 
			                                           }                 	
                                                        //console.log('------filesuccessremove---')
                                                        //console.log(data,previewId,index);
                                                        //clearUploadFile();
                                                    }).on('filedeleted', function (event, path) {
        	                                               for (var i = 0; i < picList.length; i++) { 
			                                              if (picList[i].path== path) { 
 			                                                  picList.splice(i,1);
                                                              var filePath = path.replace('/Resource/News/','')
                                                              filePath=filePath.replace('/','\\');                                   // 2022/09/15/d22d2ff2845e409b96e9576281e6d76f.png
                                                                 var ss='@UploadFileType.News.ParseToInt()';
                                                                   ys.ajax({
                                                                            url: '@GlobalContext.SystemConfig.ApiSite' + '/File/DeleteFile',
                                                                            type: "post",
                                                                             data:{
                                                                                 fileModule:'@UploadFileType.News.ParseToInt()' ,
                                                                                filePath:filePath,
                                                                              },
                                                                            success: function (obj) {
                                                                            
                                                                            }
                                                                        });

			                                                } 
			                                              }    
                                                                
                                                      });

          $('.kv-file-remove').click(function () {
              const title = $(this).parent().parent().parent().parent().find('.file-footer-caption').attr('title')

              console.log(`>>>>>>移除文件`)
              console.log(`fileUrl:${title}`)
          })

          $('.fileinput-remove-button').click(function () {
              console.log(`>>>>>>移除文件`)
              clearUploadFile()
          })
          function clearUploadFile() {
               $('input[name=fileUrl]').val("");
               $('input[name=host]').val("");
          }

          //上传图片控件结束

          $("#form").validate({
               ignore:"",
                rules: {
                    name: { required: true },
                    //age: { required: true },
                    //area:{ required: true },
                    starttime: { required: true},
                    endtime: { required: true},
                    role: {required: true},
                    chuangyio:{required: true},
                    budget:{required: true,digits:true },
                    link:{required: true}
                }
            });

        });

            function doUpload() {
              return function (event, data) {//选择即上传
                  if (!!!data[0]) {
                      $(this).fileinput("upload") // 上传文件
                  }
              };
          }

              function loadMenuTree() {
                   $('#area').ysTree({
                       async: false,
                       url: '@Url.Content("~/RedBookSetManage/RedBookSet/GetFormAreaJson")',
                       check: { enable: true },
                       expandLevel: -1
                   })
               }

               function getForm() {
                   if (id > 0) {
                       ys.ajax({
                           url: '@Url.Content("~/RedBookSetManage/RedBookSet/GetFormJson")' + '?id=' + id,
                           type: "get",
                           async:false,
                           success: function (obj) {
                               if (obj.Tag == 1) {
                                   var result = obj.Data;
                                   $("#form").setWebControls(result);
                                   $("#area").ysTree("setCheckedNodes", obj.Data.Area);
                                   $('input[name=fileUrl]').val(obj.Data.Images);
                                   if(obj.Data.Contents != null && obj.Data.Contents != undefined && obj.Data.Contents != "" && obj.Data.Contents.trim() != "")
                                   {
                                
                                     $('.summernote').summernote('pasteHTML', obj.Data.Contents);
                                   }
                                   

                                   if(!(obj.Description==null || obj.Description==""|| obj.Description==undefined))
                                   {
                                       var imagesJson=JSON.parse(obj.Description);
                                       $.each(imagesJson,function(index,value){
                                         initialPreview[index] = value.url;
                                         initialPreviewConfig[index]= {caption: value.caption, size: value.size,url:'@GlobalContext.SystemConfig.ApiSite' + '/File/DeleteFile?fileModule=@UploadFileType.News.ParseToInt()', key: value.path};
                                         picList[index]={previewId:0,path:value.path};
                                       });
                                   }
                               }
                           }
                       });
                   }
                   else {
                      var defaultData = {};
                      defaultData.setswitch = "@StatusEnum.Yes.ParseToInt()";
                      $("#form").setWebControls(defaultData);
                   }
               }

               function saveForm(index) {
                   if ($("#form").validate().form()) {

                    var ageSelect= $("#age").find("ul.select2-selection__rendered").children("li").hasClass("select2-selection__choice");
                      if(!ageSelect)
                      { layer.alert('请选择年龄！', {icon: 5});
                           return;
                      }
                       var areaCodes=$('#area').ysTree("getCheckedNodes");
                       if(areaCodes=="" || areaCodes==undefined || areaCodes==null)
                       {
                         layer.alert('请选择投放区域！', {icon: 5});
                            return ;
                       }

                      if(!$("#sex").find("div").hasClass("checked"))
                      {
                          layer.alert('请选择性别！', {icon: 5});
                           return;
                      }

                      if(!$("#setswitch").find("div").hasClass("checked"))
                      {
                          layer.alert('请选择启用状态！', {icon: 5});
                           return;
                      }

                      var postData = $("#form").getWebControls({ Id: id });
                       postData.Area=areaCodes;
                       var images=[];
                       $.each(picList,function(index,value){
                       images.push(value.path);
                       });
                       postData.Images= images.join(',');
                       postData.Contents= $('.summernote').summernote('code');
                       ys.ajax({
                           url: '@Url.Content("~/RedBookSetManage/RedBookSet/SaveFormJson")',
                           type: "post",
                           data: postData,
                           success: function (obj) {
                               if (obj.Tag == 1) {
                                   ys.msgSuccess(obj.Message);
                                   parent.searchGrid();
                                   parent.layer.close(index);
                               }
                               else {
                                   ys.msgError(obj.Message);
                               }
                           }
                       });
                   }
               }

</script>

